<template>
  <div >
    <div>
      <el-input
          v-model="selectedValue"
          :placeholder="placeholder"
          :loading="loading"
          @click="showColorPicker2"
          :id="idSelf"
          @focus="onFocus"
          clearable
          @clear="handleClear"
      >
      </el-input>

<!--      :style="{ marginTop: '10px', zIndex: 9999 }"-->
      <el-popover
          v-if="colorPickerVisible"
          v-model:visible="colorPickerVisible"
          trigger="click"
          width="300"
          :popper-style="popperStyle"
      >
        <div class="color-picker"  id="popoverId11">
          <div
              v-for="(colorRow, rowIndex) in ColorList"
              :key="rowIndex"
              class="color-row"
          >
            <div
                v-for="(color, colIndex) in colorRow"
                :key="colIndex"
                :style="styleResult(color)"
                class="color-box"
                @click="selectColor(color)"
            >
              {{getColorName(color)}}
            </div>
          </div>
        </div>
      </el-popover>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, watch, nextTick, reactive, computed} from 'vue';
import {useDictOptions} from "@/hooks/useDictOptions";

const props = defineProps({
  id: String,
  test: {
     type: Object,
     default: {},
  },
  modelValue: String,
  placeholder: {
    type: String,
    default: '请选择颜色',
  },
  // api: {
  //   type: Function,
  //   default: (query: any) => query,
  // },
  ColorList: {
    type: Array,
    default: () => [
      ['rgba(247, 103, 1, 0.1)', 'rgba(255, 148, 2, 0.1)', 'rgba(32, 195, 66, 0.1)', 'rgba(71, 36, 253, 0.1)', 'rgba(2, 83, 255, 0.1)'],
      ['rgba(255, 0, 50, 0.1)', 'rgba(50, 76, 255, 0.1)', 'rgba(123, 34, 255, 0.1)', 'rgba(255, 0, 137, 0.1)', 'rgba(241, 179, 8, 0.1)'],
      ['rgba(0, 144, 255, 0.1)', 'rgba(0, 182, 119, 0.1)', 'rgba(199, 0, 255, 0.1)', 'rgba(255, 0, 239, 0.1)', 'rgba(0, 175, 255, 0.1)']
    ]
  },
});

const emits = defineEmits(['update:modelValue','update:sonTest']);

//定义响应式坐标对象 测试对象
let test = reactive(reactive<{ x: number, y: number, xStr: string, yStr: string }>({
  x: -1.00,
  y: -2.00,
  xStr: '00',
  yStr: '00',
}))

let popperStyle = ref({ marginTop: '10px', zIndex: 9999,left: '0px', top: '0px' })
const colorArr = useDictOptions('tagColor');

const selectedValue = ref(props.modelValue);
const loading = ref(false);
const colorPickerVisible = ref(false);
const idSelf =ref(props.id);
const testFather =ref(props.test);

const showColorPicker2 = () => {
  colorPickerVisible.value = true;
    //nextTick 作用可以当做页面渲染完毕的钩子
    nextTick(() => {
      const popover = document.getElementById(idSelf?.value?.toString() || '');
      console.log('浮窗的坐标：popover', popover);
        // 获取父级元素
        const parentElement = popover?.parentElement;
        console.log('父级元素id：', parentElement?.id);
        // 确保 parentElement.style 存在后进行赋值
        if (parentElement?.style) {
          // parentElement.style.left = test.x +'px';  // 设置新的 left 值
          // parentElement.style.top =  test.y +'px';  // 设置新的 top 值
          // test.xStr = parentElement.style.left;
          // test.yStr = parentElement.style.top
        }

    });
};



const selectColor = (color: string) => {
  selectedValue.value = color;
  colorPickerVisible.value = false;
  // let test;
  // props.ColorList.forEach((colorRow : any) => {
  //   let target = colorRow?.find((item :any) => item === color);
  //   if (target){
  //     test = target;
  //     return
  //   }
  // })
  // console.log("获得对象",color);
  // console.log("获得对象",test);

  color = color.replace(')','').replace('rgb','')
  let target = colorArr.value.find((s: any) => s.detailValue.includes(color) );
  console.log("colorArr",colorArr);
  console.log("获得对象",target);

  //双绑实验
  console.log("双绑实验---原id值",idSelf.value);
  idSelf.value = 'man!'
  console.log("双绑实验---传给父对象的ID",idSelf.value);

  //双绑实验
  // console.log("双绑实验---大对象赋值2",testFather.value);
  // if (testFather?.value){
  //   testFather?.value['color'] = 'man!'
  // }
  // console.log("双绑实验---传给父对象的ID2",testFather.value);

  //console.log("双绑实验---传给父对象的ID23",selectedValue.value);

  console.log("双绑实验---传给父对象的888",testFather.value);
  emits('update:sonTest',target?.codeName)

  emits('update:modelValue', target?.codeName); // 选中颜色时通知父组件
};

const getColorName = (color: string) => {
  color = color.replace(')','').replace('rgb','')
  let target = colorArr.value.find((s: any) => s.detailValue.includes(color) );
  return target?.codeName;
}

//清除父组件数据测试 双绑测试
const handleClear = () => {
  emits('update:modelValue', '');
}



// const updateValue = () => {
//   emits('update:modelValue', selectedValue.value); // 处理输入框的值变化
// };

const onFocus= (event: any) => {
  //popoverStyle

  const inputElement = document.getElementById(idSelf?.value?.toString() || '');
  if (inputElement) {
    const rect = inputElement.getBoundingClientRect();
    test.x = rect.left ?? 0;
    let top = rect.top ?? 0;
    let height = rect.height ?? 0;
    test.y = top + height
    console.log('test`````',test)
    popperStyle.value.left =  test.x +'px'
    popperStyle.value.top =  test.y +'px'
    console.log('test`````',popperStyle)

  } else {
    console.log('无法找到元素');
  }
};

watch(() => props.modelValue, (newVal) => {
  selectedValue.value = newVal; // 监听父组件的值变化
});



const styleResult =  (color: any) => {
  let clearColor = updateColor(color);

  return { backgroundColor: color, color: clearColor, borderColor: clearColor }
};

// 去除透明度
const updateColor = (colorValue: string | undefined) => {
  if (colorValue) {
    let parts = colorValue.toString().split(',');
    if (parts.length > 3) {
      return `rgb(${parts[0].slice(5)}, ${parts[1]}, ${parts[2]})`;
    }
  }
  return colorValue;
};

// watch(colorPickerVisible, (newVal) => {
//   console.log('浮窗被赋予默认值',popoverId)
//
//   // if (newVal) {
//   //   popoverId.value = 'myPopover'; // 当弹窗可见时，设置 id
//   // } else {
//   //   popoverId.value = ''; // 隐藏时清空 id
//   // }
// });

// 监听功能测试
// watch(() => test.xStr, (newVal) => {
//   console.log('元素的坐标的x发生了变化：test', test);
//   //此时已经渲染完了？
//   const popover = document.getElementById('popoverId11');
//   console.log('浮窗的坐标：popover', popover);
//   // 获取父级元素
//   const parentElement = popover?.parentElement;
//   console.log('父级元素id：', parentElement?.id);
//   // 确保 parentElement.style 存在后进行赋值
//   if (parentElement?.style) {
//     parentElement.style.left = test.x +'px';  // 设置新的 left 值
//     parentElement.style.top =  test.y +'px';  // 设置新的 top 值
//   }
//
// });
</script>

<style scoped>
.color-picker {
  display: flex;
  flex-direction: column;
}

.color-row {
  display: flex;
  justify-content: flex-start; /* 左对齐 */
  align-items: center;         /* 垂直居中对齐 */
  margin-bottom: 10px;         /* 每行之间的间距 */
}

.color-box {
  width: 60px;   /* 每个颜色框的宽度 */
  height: 30px;  /* 每个颜色框的高度 */
  margin-right: 10px; /* 每个颜色框之间的水平间距 */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
